
package uestc.bitman.edxapp.player;

import uestc.bitman.edxapp.EdxAppConfigurations;
import uestc.bitman.edxapp.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

/**
 * @author hackeris
 * @category activity of player
 */
public class WebViewPlayerActivity extends Activity {

    private WebView mWebView = null;

    private WebSettings mWebSettings;

    private View myView = null;

    private CustomViewCallback mCallback;

    private FrameLayout mFrameLayout;

    private FullScreenChromeClient mChromeClient;

    private String mVideoUrl, mTrackUrl, mVideoTitle;

    private PlayerJavaScriptExtra jso;

    private boolean mPlayLocal = false;

    @SuppressLint("SetJavaScriptEnabled")
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        Intent intent = getIntent();
        mVideoUrl = intent.getStringExtra("video");
        mVideoTitle = intent.getStringExtra("title");
        mTrackUrl = intent.getStringExtra("track");
        mPlayLocal = intent.getBooleanExtra("local", false);
        setTitle(mVideoTitle);

        mWebView = (WebView) findViewById(R.id.player_webview);
        mFrameLayout = (FrameLayout) findViewById(R.id.player_framelayout);

        // get the webview settings
        mWebSettings = mWebView.getSettings();
        // enable javascript
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

        mWebView.setWebViewClient(new MyWebViewClient());

        mChromeClient = new FullScreenChromeClient();
        mWebView.setWebChromeClient(mChromeClient);

        // add javascript interface in web app,we can use jso to call functions
        jso = new PlayerJavaScriptExtra(this);
        mWebView.addJavascriptInterface(jso, "jso");

        // load test page
        // webView.loadUrl("http://10.50.46.37:8000/");
        mWebView.loadUrl(EdxAppConfigurations.LOCAL_PLAYER_URL);
        /*
         * if (playLocal) {
         * webView.loadUrl(EdxAppConfigurations.LOCAL_PLAYER_URL); } else {
         * webView.loadUrl(EdxAppConfigurations.ONLINE_PLAYER_URL); }
         */

        if (savedInstanceState != null) {
            mWebView.restoreState(savedInstanceState);
        }
    }

    /**
     * If in full screen mode and the user pressed back,exit full screen
     */
    @Override
    public void onBackPressed() {

        if (myView == null) {
            super.onBackPressed();
        } else {
            mChromeClient.onHideCustomView();
        }
    }

    /**
     * Orentation changed
     */
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    /**
     * We can use back like a browser
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack() && myView == null) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onPause() {

        // Call function pause() in web page
        mWebView.loadUrl("javascript:pause()");
        // If the current activity is finished,load the webView with blank page
        if (isFinishing()) {
            mWebView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
        super.onPause();
    }

    public void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }

    public void onStop() {

        mWebView.stopLoading();
        mWebView.loadUrl("javascript:pause()");
        super.onStop();
    }

    /**
     * Quit full screen
     */
    private void quitFullScreen() {

        // requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        final WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(attrs);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

    /**
     * Enter full screen
     */
    private void enterFullScreen() {

        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public class MyWebViewClient extends WebViewClient {

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

            WebResourceResponse response = null;
            response = super.shouldInterceptRequest(view, url);
            return response;
        }
    }

    public String getVideoUrl() {
        if (mPlayLocal) {
            return "file://" + mVideoUrl;
        }
        return mVideoUrl;
    }

    public String getTrackUrl() {
        if (mTrackUrl == null || mTrackUrl.equals("")) {
            return mVideoUrl.replace(".mp4", ".srt");
        }
        return mTrackUrl;
    }

    public String getTrackString() {
        if (mPlayLocal) {
            return jso.readTrackFromFile(getTrackUrl());
        } else {
            return jso.urlDownloadToString(getTrackUrl());
        }
    }

    /**
     * @author hackeris
     * @category WebChromeClient of full screen
     */
    public class FullScreenChromeClient extends WebChromeClient {

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {

            if (myView != null) {
                callback.onCustomViewHidden();
                return;
            }
            mFrameLayout.removeView(mWebView);
            mFrameLayout.addView(view);
            // the landscape screen orientation
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            // enter fullscreen
            enterFullScreen();
            myView = view;
            mCallback = callback;
        }

        @Override
        public void onHideCustomView() {

            if (myView == null) {
                return;
            }
            mFrameLayout.removeView(myView);
            mFrameLayout.addView(mWebView);
            myView = null;
            // The portrait screen orientation
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            // Quit fullscreen
            quitFullScreen();
            mCallback.onCustomViewHidden();
        }
    }
}
